# Author: Sanmu
# CreatTime: 2024/10/24
# Descriptior: 基类，对webdrive的封装
import traceback
from time import sleep

import ddddocr
from selenium.webdriver.support.select import Select

from conf.set_conf import read_conf


class BasePage:
    def __init__(self, driver):
        self.driver = driver
        self.driver.implicitly_wait(5)
    # 访问url
    def open(self,path):
        url = self.get_url(path)
        self.driver.get(url)
    #定位元素
    def locator(self,by,value):
        return self.driver.find_element(by,value)
    #输入内容
    def input(self,by,value,text):
        el = self.locator(by,value)
        el.clear()
        el.send_keys(text)
    #点击按钮
    def click(self,by,value):
        # bt = self.locator(by,value)
        # self.driver.execute_script('$arguments[0].click()',bt)
        self.locator(by,value).click()
    #下拉框
    def select(self,by,value,text):
        se = Select(self.locator(by,value))
        return se.select_by_visible_text(text)
    # 单选框
    def radio(self,by,value):
        radio_button = self.locator(by, value)
        if not radio_button.is_selected():
            radio_button.click()
    #复选框
    def checkbox(self,by,value):
        checkboxes = self.driver.find_elements(by,value)
        #遍历选择
        for checkbox in checkboxes:
            if checkbox.is_selected():
                pass
            else:
                checkbox.click()
    #alter弹窗
    def alter(self):
        return self.driver.switch_to.alert
    #读取验证码
    def cor_code(self, by, value):
        ocr_png = self.locator(by, value).screenshot_as_png
        code = ddddocr.DdddOcr(show_ad=False).classification(ocr_png)
        return code
    #断言
    def assert_text(self,by,value,expected):
        try:
            reality = self.locator(by,value).text
            assert reality == expected, f'''
                预期结果：{expected},
                实际结果：{reality},
                断言结果：{expected} != {reality}，断言失败！
            '''
            return True
        except:
            traceback.print_exc()
            return False
    # 异常截图
    def get_png(self):
        return self.driver.get_screenshot_as_png()
    #强制等待
    def wait(self,time_):
        sleep(int(time_))
    #关闭浏览器
    def quit(self):
        self.driver.quit()

    # 拼接url
    def get_url(self, path):
        host = read_conf('TEST_ENV', 'host')
        port = read_conf('TEST_ENV', 'port')
        return host + ':' + port + path